<template>
  <div class="front">
    <el-form :model="searchForm" label-width="120px">
      <el-form-item class="input" label="供应商名字">
        <el-input v-model="searchForm.supplierName" />
      </el-form-item>
    </el-form>
    <el-button class="search" type="primary" @click="onSearch()">查询</el-button>
  </div>


  <div class="tail">
    <div class="tail-action">
      <el-button type="primary" @click="openAdd">新增供应商</el-button>
      <el-button  type="primary"  @click="handleChangeStatus">启用</el-button>
      <el-button  type="primary"  @click="handleChangeStatus1">停用</el-button> 
    </div>
    <el-table :data="tableData()" border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" />
      <el-table-column prop="supplierCode" label="供应商编码" min-width="60" />
      <el-table-column prop="supplierName" label="供应商名称" min-width="60" />
      <el-table-column prop="buyerName" label="采购员工名称" min-width="60" />
      <el-table-column prop="supplierType" label="供货商性质" min-width="60" />
      <el-table-column prop="buyerPhone" label="员工手机号/对接人手机号" min-width="60" />
      <el-table-column prop="buyerName" label="供应商对接人姓名" min-width="60" />
      <el-table-column prop="buyerIdcard" label="采购员工身份证号" min-width="60" />
      <el-table-column prop="payeeName" label="账户名" min-width="60" />
      <el-table-column prop="payeeBank" label="开户银行" min-width="60" />
      <el-table-column prop="settlementWay" label="结款模式" min-width="60" />
      <el-table-column prop="settlementType" label="结算方式" min-width="60" />
      <el-table-column prop="address" label="地址" min-width="60" />
      <el-table-column prop="createTime" label="创建时间" min-width="60" />
      <el-table-column prop="status" label="商户状态" width="100" :filter-multiple="false" :filters="[
  { text: '停用', value: 1 },
  { text: '启用', value: 0 },
]" :filter-method="filterTag" filter-placement="bottom-end">
  <template #default="scope">
    <el-tag :type="scope.row.status == 0? 'success' : 'danger'" disable-transitions>{{ scope.row.status == 1? '停用' : '启用' }}</el-tag>
  </template>
</el-table-column>
      <el-table-column prop="remark" label="备注" min-width="60" />
      <el-table-column fixed="right" label="操作" min-width="60">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="openEdit(scope.row)">编辑</el-button>
          <el-button link type="primary" size="small" @click="handleDeleteRole(scope.row.id)">删除</el-button>
         

        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination v-model="data.page" :page-size="data.limit"
        layout="prev, pager, next,total,sizes" :total="data.total" @current-change="handleCurrentChange"
        @size-change="handleSizeChange" />
    </div>
  </div>

  <div class="dialog-list">
    <el-dialog v-model="dialogVisible1" title="新建供应商" width="35%" :close-on-click-modal="true" @close="handleClose"
      destroy-on-close :show-close="false">
      <div>
        <el-form :model="supplierForm" label-width="120px" :rules="supplierRules" ref="supplierRef">
          <el-form-item label="供应商编码" prop="supplierCode" :required="true">
            <el-input v-model="supplierForm.supplierCode" disabled />
          </el-form-item>

          <el-form-item label="供货商性质" prop="supplierType" :required="true">
            <el-select v-model="supplierForm.supplierType" placeholder="请选择供货商性质" @change="changeType()">
              <el-option label="采购员工" value="采购员工" />
              <el-option label="外部供应商" value="外部供应商" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="supplierType" label="采购员工姓名" prop="buyerName" :required="true">
            <el-input v-model="supplierForm.buyerName" />
          </el-form-item>
          <el-form-item v-if="supplierType" label="采购员工身份证号" :required="true">
            <el-input v-model="supplierForm.buyerIdcard" />
          </el-form-item>
          <el-form-item v-if="supplierType" label="采购员工手机号" prop="buyerPhone" :required="true">
            <el-input v-model="supplierForm.buyerPhone" />
          </el-form-item>
          <el-form-item label="供应商名称" prop="supplierName" :required="true">
            <el-input v-model="supplierForm.supplierName" />
          </el-form-item>
          <el-form-item v-if="!supplierType" label="供应商对接人姓名" prop="buyerName" :required="true">
            <el-input v-model="supplierForm.buyerName" />
          </el-form-item>
          <el-form-item v-if="!supplierType" label="供应商对接人手机号" prop="buyerPhone" :required="true">
            <el-input v-model="supplierForm.buyerPhone" />
          </el-form-item>
          <el-form-item label="地址">
            <el-input v-model="supplierForm.address" />
          </el-form-item>
          <el-form-item label="结款模式" :required="true">
            <el-select v-model="supplierForm.settlementWay" placeholder="请选择结款模式" @change="changeMode()">
              <el-option label="银行转账" value="银行转账" />
              <el-option label="支付宝转账" value="支付宝转账" />
              <el-option label="微信转账" value="微信转账" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
          <el-form-item label="收款人姓名" :required="true">
            <el-input v-model="supplierForm.payeeName" />
          </el-form-item>
          <el-form-item label="收款人账号" :required="true">
            <el-input oninput="value=value.replace(/[^\d]/g,'')" v-model="supplierForm.payeeAccount" />
          </el-form-item>
          <el-form-item label="收款人开户行" :required="true">
            <el-input v-model="supplierForm.payeeBank" />
          </el-form-item>
          <el-form-item label="结算方式" :required="true">
            <el-select v-model="supplierForm.settlementType" placeholder="请选择结算方式" @change="changeWay()">
              <el-option label="成本价百分比结算" value="成本价百分比结算" />
              <el-option label="标签价百分比结算" value="标签价百分比结算" />
            </el-select>
          </el-form-item>
          <el-form-item label="结算比率" v-if="supplierForm.settlementType === '成本价百分比结算' || supplierForm.settlementType === '标签价百分比结算'">
            <el-input v-model="supplierForm.settlementRatio" @input="addUnitt" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="supplierForm.remark" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible1 = false">取消</el-button>
          <el-button type="primary" @click="handleAddSupplier">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogVisible2" title="编辑供应商" width="30%" :close-on-click-modal="true" @close="handleClose()"
      :show-close="false" destroy-on-close>
      <div>
        <el-form :model="supplierForm" label-width="120px" :rules="supplierRules" ref="supplierRef">
          <el-form-item label="供货商性质" prop="supplierType" :required="true">
            <el-select v-model="supplierForm.supplierType" placeholder="请选择供货商性质" @change="changeType()">
              <el-option label="采购员工" value="采购员工" />
              <el-option label="外部供应商" value="外部供应商" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="supplierType" label="采购员工姓名" prop="buyerName" :required="true">
            <el-input v-model="supplierForm.buyerName" />
          </el-form-item>
          <el-form-item v-if="supplierType" label="采购员工身份证号" :required="true">
            <el-input v-model="supplierForm.buyerIdcard" />
          </el-form-item>
          <el-form-item v-if="supplierType" label="采购员工手机号" prop="buyerPhone" :required="true">
            <el-input v-model="supplierForm.buyerPhone" />
          </el-form-item>
          <el-form-item label="供应商名称" prop="supplierName" :required="true">
            <el-input v-model="supplierForm.supplierName" />
          </el-form-item>
          <el-form-item v-if="!supplierType" label="供应商对接人姓名" prop="buyerName" :required="true">
            <el-input v-model="supplierForm.buyerName" />
          </el-form-item>
          <el-form-item v-if="!supplierType" label="供应商对接人手机号" prop="buyerPhone" :required="true">
            <el-input v-model="supplierForm.buyerPhone" />
          </el-form-item>
          <el-form-item label="地址">
            <el-input v-model="supplierForm.address" />
          </el-form-item>
          <el-form-item label="结款模式" :required="true">
            <el-select v-model="supplierForm.settlementWay" placeholder="请选择结款模式" @change="changeMode()">
              <el-option label="银行转账" value="银行转账" />
              <el-option label="支付宝转账" value="支付宝转账" />
              <el-option label="微信转账" value="微信转账" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
          <el-form-item label="收款人姓名" :required="true">
            <el-input v-model="supplierForm.payeeName" />
          </el-form-item>
          <el-form-item label="收款人账号" :required="true">
            <el-input oninput="value=value.replace(/[^\d]/g,'')" v-model="supplierForm.payeeAccount" />
          </el-form-item>
          <el-form-item label="收款人开户行" :required="true">
            <el-input v-model="supplierForm.payeeBank" />
          </el-form-item>
          <el-form-item label="结算方式" :required="true">
            <el-select v-model="supplierForm.settlementType" placeholder="请选择结算方式" @change="changeWay()">
              <el-option label="成本价百分比结算" value="成本价百分比结算" />
              <el-option label="标签价百分比结算" value="标签价百分比结算" />
            </el-select>
          </el-form-item>
          <el-form-item label="结算比率" v-if="supplierForm.settlementType === '成本价百分比结算' || supplierForm.settlementType === '标签价百分比结算'">
            <el-input v-model="supplierForm.settlementRatio" @input="addUnitt" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="supplierForm.remark" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible2 = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateSupplier">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>
     
<script >
import { ref, defineComponent, reactive, toRefs, } from "vue";
import { ElMessageBox, ElMessage } from 'element-plus'
import { onMounted } from "vue";
import { getSupplierList, addSupplier, deleteSupplier, updateSupplier, getSupplierCode } from '@/api/user/user'

import { changeSupplierStatus } from '@/api/auth/auth';
import axios from 'axios';

export default defineComponent({
  name: "UserRole",
  components: {},

  setup() {
    let selectedRows = ref([]); // 使用ref来响应式地初始化selectedRows
    let supplierData = reactive({ //表格数据
      data: [],
    });
    
    const supplierRef = ref(null)
    const supplierType = ref(false)//控制ui
    const supplierForm = reactive({
      id:'',
      supplierCode: '',
      supplierName: '',
      supplierType: "",
      address: "",
      buyerName: "",
      buyerPhone: "",
      buyerIdcard: "",
      settlementWay: "",
      payeeName: "",
      payeeAccount: "",
      payeeBank: "",
      settlementType: "",
      startTime: "",
      deptId: "1",

      status:0,
      options: [
        {value: 0,label: '启用'},
        {value: 1,label: '禁用'},
      ]
    });
    const searchForm = reactive({
      supplierName: '',
      status: 0,  //yyl添加
    });
    
    let dialogVisible1 = ref(false)
    const dialogVisible2 = ref(false)
    const supplierRules = reactive({
      supplierName: [{ required: true, message: '请输入内容', trigger: 'blur' },
      { min: 2, max: 8, message: '名称长度在 2 到 8长度之间', trigger: 'blur' }],
      supplierType: [{ required: true, message: '该选项不能为空', trigger: 'blur' }],
      buyerName: [{ required: true, message: '请输入内容', trigger: 'blur' },
      { min: 2, max: 8, message: '名称长度 在 2 到 8长度之间', trigger: 'blur' }],
      buyerPhone: [{ required: true, message: '请输入内容', trigger: 'blur' }, {
        type: 'number',
        message: '手机号格式不正确',
        trigger: 'blur',
        transform(value) {
          var phonereg = 11 && /^((13|14|15|16|17|18|19)[0-9]{1}\d{8})$/
          if (!phonereg.test(value)) {
            return false
          } else {
            return Number(value)
          }
        }
      }]
    });


    //表格用到的参数
    let state = reactive({
      data: {
        page: 1,
        limit: 10,
        total: supplierData.data.length,
      }
    });

    const filterTag = (value, row) => {
      return row.status == value
    }
    onMounted(() => {
      handleGetSupplierList(state.data.page, state.data.limit)
    })


    const handleGetSupplierList = (page, limit) => {
  getSupplierList(page, limit).then((res) => {
    supplierData.data = res.rows;
    state.data.total = res.total;
  });
};
    //分页处理
    const tableData = () => {
      return supplierData.data
    };
    //改变页码
    const handleCurrentChange = (e) => {
      state.page = e;
      handleGetSupplierList(e, state.data.limit)
    };
    //改变页数限制
    const handleSizeChange = (e) => {
      state.limit = e;
      handleGetSupplierList(state.data.page, e)
    };

    const openAdd = () => {
      dialogVisible1.value = true
      getSupplierCode().then((res) => {
        supplierForm.supplierCode = res
      })
    }
    //添加供应商
    const handleAddSupplier = () => {
      supplierRef.value.validate().then(() => {//验证通过
        addSupplier(supplierForm).then((res) => {
          res.code == 200 ? ElMessage.success('添加成功') : ElMessage.error(res.msg)
          clearForm()
          dialogVisible1.value = false
          handleGetSupplierList(state.data.page, state.data.limit)
        })
      }).catch(()=>{
        
      })
    }

    const changeType = () => {
      if (supplierForm.supplierType == '采购员工') {
        supplierType.value = true
      } else {
        supplierType.value = false
      }

    }
    const changeWay = () => {

    }
    const changeMode = () => {

    }
    const handleDeleteRole = (supplierId) => { //删除仓位
      ElMessageBox.confirm(
        '是否要删除该用户?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          deleteSupplier(supplierId).then(() => {
            handleGetSupplierList(state.data.page, state.data.limit)
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
          })
        }).catch(() => {
          ElMessage({
            type: 'info',
            message: '取消操作',
          })
        })
    }

    const openEdit = (data) => { //打开编辑仓位
      dialogVisible2.value = true
      supplierForm.id=data.id
      supplierForm.supplierName = data.supplierName
      supplierForm.remark = data.remark
      supplierForm.address = data.address
      supplierForm.buyerPhone = data.buyerPhone
      supplierForm.buyerName = data.buyerName
      supplierForm.payeeAccount = data.payeeAccount
      supplierForm.payeeName = data.payeeName
      supplierForm.payeeBank = data.payeeBank
      supplierForm.buyerIdcard = data.buyerIdcard
      
    }
    const clearForm = () => {
      supplierForm.supplierName = ''
      supplierForm.remark = ''
      supplierForm.address = ''
      supplierForm.buyerPhone = ''
      supplierForm.buyerName = ''
      supplierForm.payeeAccount = ''
      supplierForm.payeeName = ''
      supplierForm.payeeBank = ''
      supplierForm.buyerIdcard = ''
      
    }

    const handleUpdateSupplier = () => {  //编辑仓位
      supplierRef.value.validate().then(() => {//验证通过
        ElMessageBox.confirm('确认提交?')
          .then(() => {
            updateSupplier(supplierForm).then((res) => {
              if (res.code == 200) {
                ElMessage.success('修改成功')
              } else {
                ElMessage.error(res.msg)
              }
              dialogVisible2.value = false
              handleGetSupplierList(state.data.page, state.data.limit)
              clearForm()
            })
          })
          .catch(() => {
            // catch error
          })
      }).catch(()=>{

      })
    }
    const handleClose = (formRef) => { //对话框关闭回调
      clearForm()
    }
    const onSearch=()=>{
      getSupplierList(state.data.page, state.data.limit, searchForm.supplierName).then((res) => {
        supplierData.value = res.rows
        state.data.total = res.total
      })
    }
    //切换商户状态

const handleSelectionChange = (val) => {
  selectedRows = val;
};
//启用
const handleChangeStatus = async () => {
  if (selectedRows.length === 0) {
    ElMessage.warning('请至少选择一个供应商进行操作');
    return;
  }

  const selectedRow = selectedRows[0];
  const statusValue = Number(selectedRow.status);
  console.log('当前状态值：', statusValue);

  let newStatus;
  if (statusValue === 0) {
    // 状态为 0（启用）时无需改变状态，但可以给出提示信息
    ElMessage.info('当前状态为启用状态，无需改变');
    return;
  } else if (statusValue === 1) {
    // 状态为 1（停用）时改为 0（启用）
    newStatus = 0;
  } else {
    ElMessage.warning('未知状态');
    return;
  }

  if (newStatus!== undefined) {
    const wmsBasicClientObject = {
      id: Number(selectedRow.id),
      status: newStatus.toString()
    };

    try {
      const result = await changeSupplierStatus(wmsBasicClientObject);

      if (result.code === 200) {
        selectedRow.status = newStatus;
        handleGetSupplierList(state.data.page, state.data.limit);
        ElMessage.success('状态更新成功');
      } else {
        ElMessage.error(result.msg || '状态更新失败');
      }
    } catch (error) {
      console.error('状态更新请求失败:', error);
      ElMessage.error('状态更新请求失败');
    }
  }
};
//停用
const handleChangeStatus1 = async () => {
  if (selectedRows.length === 0) {
    ElMessage.warning('请至少选择一个供应商进行操作');
    return;
  }

  const selectedRow = selectedRows[0];
  // 添加数据类型检查和调试信息
  const statusValue = Number(selectedRow.status);
  console.log('当前状态值：', statusValue);

  if (statusValue === 0) {
    const newStatus = 1;
    const wmsBasicClientObject = {
      id: Number(selectedRow.id),
      status: newStatus.toString()
    };

    try {
      const result = await changeSupplierStatus(wmsBasicClientObject);

      if (result.code === 200) {
        selectedRow.status = newStatus;
        handleGetSupplierList(state.data.page, state.data.limit);
        ElMessage.success('状态更新成功');
      } else {
        ElMessage.error(result.msg || '状态更新失败');
      }
    } catch (error) {
      console.error('状态更新请求失败:', error);
      ElMessage.error('状态更新请求失败');
    }
  } else if (statusValue === 1) {
    ElMessage.info('当前状态为停用状态，无需改变');
  } else {
    ElMessage.warning('未知状态');
  }
};
    return {
      supplierData, supplierRef,
      dialogVisible1, supplierType,
      dialogVisible2,
      searchForm,
      supplierForm,
      supplierRules,
      tableData, filterTag,handleSelectionChange,
      handleCurrentChange,
      handleSizeChange, openAdd,handleChangeStatus,
      handleClose, changeType, changeWay, changeMode,handleChangeStatus1,
      handleDeleteRole, handleAddSupplier, handleGetSupplierList, handleUpdateSupplier,
      openEdit,onSearch,
      ...toRefs(state),
    };
   
    
  },
  
});
//实现点击成本价百分比结算或者标签价百分比结算弹出结算比率
const supplierForm = {
  methods: {
    handleSelectChange() {
      if (supplierForm.settlementType === '成本价百分比结算' || supplierForm.settlementType === '标签价百分比结算') {
        supplierForm.settlementRatio = '';
        this.$nextTick(() => {
          this.$refs.settlementRatio.focus();
        });
      } else {
        supplierForm.settlementRatio = '';
      }
    },
  }
};

// 暴露 supplierForm 对象
export { supplierForm };




</script>
    
<style rel="stylesheet/scss" lang="scss" scoped>
.front {
  background-color: #fff;
  padding: 10px;
  display: flex;

  .input {
    float: left;
  }

  .search {
    margin-left: 50px;
  }
}

.center {
  margin: 10px;
}

.form-add-checkbox {
  width: 200px;
  height: 260px;
  display: block;
  border: solid 1px #c9c9c9;

  .form-add-checkbox-item {
    width: 180px;
    margin: auto;
  }
}

.tail {
  background-color: #fff;
  margin-top: 40px;
  padding: 10px;

  .tail-action {
    margin-bottom: 10px;
    display: flex;
  }
}
</style>